package android.hermes;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import java.lang.Number;


import android.app.Activity;
import android.content.Context;
import android.hermes.R.id;
import android.hermes.R.layout;
import android.hermes.R.raw;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


/**
 *  
 * @author Erik, Tobias & Joakim.
 *
 */

@SuppressWarnings("unused")
public class Hermes extends Activity implements OnClickListener {
	
	//instance varibles
	WifiManager wifi = null;
	Button sendButton, listenButton;
	EditText txtBox;
	TextView inbox;
	AdHocWifiManager adhocWifi;
	

    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        adhocWifi = new AdHocWifiManager();
        
        //the listen button
        listenButton = (Button) findViewById(R.id.listenButton);
        listenButton.setOnClickListener(this);
        //the send botton
        sendButton = (Button) findViewById(R.id.sendButton);
        sendButton.setOnClickListener(this);
        //the textbox where you write the textmessage
        txtBox = (EditText) findViewById(R.id.txtBox);
        inbox = (TextView) findViewById(R.id.inbox);
        
        //disable wifi
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifi.setWifiEnabled(false);
        
        //create dir and move bin
        createDirs();
        moveFiles();
        
        
    }
    
    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    public void onClick(View v) {
    	if(v == listenButton){
    		popMsg("Starting to listen");
	        //waits for standard wifi-manager to finish disabling
	        while(wifi.getWifiState() == WifiManager.WIFI_STATE_DISABLING){}
	        if(adhocWifi.disableWifi())
	        	
	        //enables wifi, or error message
	        if(!adhocWifi.enableWifi(1)){
	        	popMsg("not enable network");
	        }
	        //sets up the socketlistner
	        setupSocketListener();
	        
    	}
    	else if(v == sendButton){
    		popMsg("Starting to send");
    		
    		adhocWifi.disableWifi();
    		//enables wifi, or error message
	        if(!adhocWifi.enableWifi(2)){
	        	popMsg("not enable network");
	        }
	        
	        //connects to hermes
	        if(!adhocWifi.connect()){
	        	popMsg("not connect");
	        }
	        for(int i=0; i<9000000; i++){
	        	if(i%3000000 == 0){
	        		popMsg("Hold on " +i);
	        	}
	        }
	        //starts sending
	        send();
    	}
    	else{
    		popMsg("button error");
    	}
    
    }

	/**
	 * (non-Javadoc)
	 * @see android.os.Handler#handleMessage(android.os.Message)
	 * 
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			String x = (String) msg.obj;
			//Context context = getApplicationContext();
			
			inbox.setText(inbox.getText() + x);
			
			popMsg(x);
			
			//printInbox(x);
		}
	};
	
	/**
	 * 
	 */
	private void send(){
    	try {
    		    		
    		InetAddress ip = InetAddress.getByName("192.168.42.101");
    		popMsg("skickat till: " +ip.toString());
			Socket sendSocket = new Socket(ip, 6546);
			
			DataOutputStream utdata = new DataOutputStream(sendSocket.getOutputStream());
			
			utdata.writeBytes(txtBox.getText() +"\n");
			sendSocket.close();
			
		} catch (Exception e) {
			//error handling
			Hermes.this.popMsg(e.getMessage());
		} 
    	
    }

    /**
     * creates and starts a thread that handles the socketlistener
     */
    private void setupSocketListener(){
    	Thread t = new Thread (new Runnable(){
    		public void run(){
    			while(true){
    			Socket connectionSocket;
    			BufferedReader indata;
    
	    			try {
    					ServerSocket welcomeSocket = new ServerSocket(6546);
						String tempS;				
						connectionSocket = welcomeSocket.accept();
						indata = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
												
						Message msg = new Message();
						tempS = indata.readLine();
						msg.obj = tempS;
						
						handler.sendMessage(msg);
						connectionSocket.close();
						welcomeSocket.close();
						
					} catch (IOException e) {
						//error handling
						Hermes.this.popMsg("fel vid lyssning");
					}
    			}
    		}
    	});
    	t.start();

    }
    /**
     * @param message
     * Displays a simple toast 
     */
    public void popMsg(String message) {
    	Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}
    


    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * Create the necessary directories
     */
    private void createDirs() {
    	File dir = new File("/data/data/android.hermes/");
    	if (dir.exists() == false) {
    			Hermes.this.popMsg("Application data-dir does not exist!");
    	}
    	else {
	    	dir = new File("/data/data/android.hermes/bin");
	    	if (dir.exists() == false) {
	    		if (!dir.mkdir()) {
	    			Hermes.this.popMsg("Couldn't create bin-directory!");
	    		}
	    	}
	    	dir = new File("/data/data/android.hermes/conf");
	    	if (dir.exists() == false) {
	    		if (!dir.mkdir()) {
	    			Hermes.this.popMsg("Couldn't create conf-directory!");
	    		}
	    	}
	    	dir = new File("/data/data/android.hermes/Sockets");
	    	if (dir.exists() == false) {
	    		if (!dir.mkdir()) {
	    			Hermes.this.popMsg("Couldn't create Sockets-directory!");
	    		}
	    	}
    	}
    	
    }
    /**
     * Copies the essential files to their places, and makes some executable.
     */
    private void moveFiles() {
    	
    	
    	//wpaX.conf
    	this.copyBinary("/data/data/android.hermes/conf/wpa.conf", R.raw.wpa_conf);
    	this.copyBinary("/data/data/android.hermes/conf/tiwlan.ini", R.raw.tiwlan_ini);

    	/*
    	// wifi
    	this.copyBinary("/data/data/android.hermes/bin/wifi", R.raw.wifi);
    	this.copyBinary("/data/data/android.hermes/bin/connect", R.raw.connect);
    	
    	//Change rights to be able to execute the shell scripts
    	runRootCommand("chmod 777 /data/data/android.hermes/bin/wifi");
    	runRootCommand("chmod 777 /data/data/android.hermes/bin/connect");
    	*/
    }
    
    //Creates a file from a resource, "copying" it.
    private void copyBinary(String filename, int resource) {
    	File outFile = new File(filename);
    	InputStream is = this.getResources().openRawResource(resource);
    	byte buf[]=new byte[1024];
        int len;
        try {
        	OutputStream out = new FileOutputStream(outFile);
        	while((len = is.read(buf))>0) {
				out.write(buf,0,len);
			}
        	out.close();
        	is.close();
		} catch (IOException e) {
			Hermes.this.popMsg("Couldn't install file - "+filename+"!");
		}
    }
}

